# Copyright 1999-2011 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: $

EAPI=2

inherit eutils games cdrom unpacker

MY_PV="2.5.02-${PV}"
MY_UPD="http://updatefiles.linuxgamepublishing.com/${PN}"

DESCRIPTION="Open-ended space opera with trading, building & fighting"
HOMEPAGE="http://www.linuxgamepublishing.com/info.php?id=x3"
# Patches are in http://updatefiles.linuxgamepublishing.com/x3/
SRC_URI="${MY_UPD}/${PN}-2.5-2.5.01-x86.run
	${MY_UPD}/${PN}-2.5.01-2.5.02-x86.run
	${MY_UPD}/${PN}-${MY_PV}-x86.run"

LICENSE="as-is"
SLOT="0"
KEYWORDS="amd64 x86"
IUSE="bonuspack modkit"

LANGS="de fr it"
for L in ${LANGS}; do
	IUSE="${IUSE} linguas_${L/-/_}"
done

RESTRICT="strip primaryuri"

RDEPEND="|| ( media-sound/oss media-sound/oss-devel media-libs/alsa-lib )
	sys-libs/glibc
	x86? (
		media-libs/libsdl
		media-libs/openal
		sys-libs/zlib
		x11-libs/gtk+
		x11-libs/libX11
		x11-libs/libXau
		x11-libs/libXdmcp
		x11-libs/libXext
		x11-libs/libXi )
	amd64? (
		app-emulation/emul-linux-x86-gtklibs
		app-emulation/emul-linux-x86-sdl )"
DEPEND=""

S=${WORKDIR}

unpackit() {
	unpack "./cd/data/${1}.tar.gz"
}

src_unpack() {
	cdrom_get_cds .data/bin/Linux/x86/${PN}
	ln -sfn "${CDROM_ROOT}"/.data cd

	unpackit x3
	unpackit datfiles
	unpackit mov
	use bonuspack && unpackit bonuspack
	use linguas_de && unpackit de_lang
	use linguas_fr && unpackit fr_lang
	use linguas_it && unpackit it_lang
	use modkit && unpackit modkit

	rm -f cd

	cp -rf "${CDROM_ROOT}"/.data/bin/Linux/x86/* . || die "cp exes"
	cp -f "${CDROM_ROOT}"/.data/icon.xpm . || die "cp icon"
	cp -f "${CDROM_ROOT}"/READ* . || die "cp READ*"

	# Mission Director, a tool for mission development, was introduced with patch 2.5
	mkdir director
	touch director/.keep
	
	# Apply the patches
	local p
	for p in 2.5-2.5.01 2.5.01-2.5.02 "${MY_PV}" ; do
		einfo "Applying patch ${p}"
		mkdir patch
		cd patch
		unpack_makeself "${PN}-${p}-x86.run"
		bin/Linux/x86/loki_patch patch.dat "${S}" \
			|| die "loki_patch ${p}"
		cp -f README.txt "${S}/ChangeLog" || die "cp README.txt"
		cd "${S}"
		rm -rf patch
	done
	
	# Description clean-up
	use linguas_de || rm description/*Deutsch*.xml
	use linguas_fr || rm description/*Fran*.xml
	use linguas_it || rm description/*Italiano*.xml
}

src_install() {
	local dir=${GAMES_PREFIX_OPT}/${PN}

	insinto "${dir}"
	doins -r * || die "doins -r"

	exeinto "${dir}"
	doexe x3* || die "doexe x3*"

	if use modkit ; then
		exeinto "${dir}"/modkit
		doexe modkit/x3{build,tool} || die "doexe modkit"
		local f
		for f in build tool ; do
			games_make_wrapper "x3${f}" "${dir}/modkit/x3${f}"
		done
	fi

	games_make_wrapper ${PN} "./${PN}-launcher" "${dir}"
	newicon "${CDROM_ROOT}"/.data/icon.xpm ${PN}.xpm || die "newicon"
	make_desktop_entry ${PN} "X3 - Reunion" ${PN}

	prepgamesdirs
}

pkg_postinst() {
	games_pkg_postinst
}
